package com.xiaoshuidi.cloud.module.finance.util.pdf;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

public class PdfToImgUtil {


    /**
     * 转换全部的pdf
     */
    public static List<Image> pdf3png(InputStream inputStream, float dpi) {
        // 将pdf装图片 并且自定义图片得格式大小
        List<Image> images = new LinkedList<Image>();
        try {
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(bufferedImage, "png", outputStream);

                byte[] imageBytes = outputStream.toByteArray();
                images.add(Image.getInstance(imageBytes));

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        }
        return images;
    }
}
